package weixin.processer.message;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;

import models.Article;
import models.ArticleMulti;
import models.Reply;
import models.Weixin;
import net.ufrog.common.utils.Strings;
import play.Logger;
import play.Play;
import weixin.Converters;
import weixin.WXMessage;
import weixin.WXMessage.Item;

/**
 * 自动回复消息处理实现
 * 
 * @author ultrafrog
 * @version 1.0, 2014-12-24
 * @since 1.0
 */
public class ReplyMessageProcesser extends WXMessageProcesser {

	/* (non-Javadoc)
	 * @see weixin.processer.message.WXMessageProcesser#process(weixin.WXMessage, weixin.WXMessage)
	 */
	@Override
	public Boolean process(WXMessage wxmsg, WXMessage bkmsg) {
		// 初始化并查询数据
		Reply reply = null;
		List<Reply> replys = new ArrayList<Reply>();
		Weixin weixin = Weixin.find("byOriginalCode", wxmsg.toUserName).first();
		
		// 内容匹配
		matchPerfect(wxmsg.content, Reply.getPerfectMatching(weixin.id), replys);
		matchPartial(wxmsg.content, Reply.getPartialMatching(weixin.id), replys);
		matchDefault(Reply.getDefaultMatching(weixin.id), replys);
		
		// 随机返回内容
		if (replys.size() == 1) {
			reply = replys.get(0);
		} else if (replys.size() > 1) {
			Random random = new Random();
			reply = replys.get(random.nextInt(replys.size()));
		}
		
		// 输出内容
		Logger.debug("find reply %s", replys);
		if (reply != null) {
			Converters.replyToMessage(reply, bkmsg);
		}
		
		// 返回结果
		return Boolean.TRUE;
	}
	
	/**
	 * 完全匹配
	 * 
	 * @param content
	 * @param map
	 * @param replys
	 */
	protected void matchPerfect(String content, Map<String, List<Reply>> map, List<Reply> replys) {
		if (Strings.empty(content)) return;
		for (Entry<String, List<Reply>> entry: map.entrySet()) {
			if (Strings.equals(content, entry.getKey())) {
				replys.addAll(entry.getValue());
			}
		}
	}
	
	/**
	 * 部分匹配
	 * 
	 * @param content
	 * @param map
	 * @param replys
	 */
	protected void matchPartial(String content, Map<String, List<Reply>> map, List<Reply> replys) {
		if (Strings.empty(content)) return;
		for (Entry<String, List<Reply>> entry: map.entrySet()) {
			if (content.indexOf(entry.getKey()) >= 0) {
				replys.addAll(entry.getValue());
			}
		}
	}
	
	/**
	 * 默认匹配
	 * 
	 * @param map
	 * @param replys
	 */
	protected void matchDefault(Map<String, List<Reply>> map, List<Reply> replys) {
		if (replys.size() > 0) return;
		for (Entry<String, List<Reply>> entry: map.entrySet()) {
			replys.addAll(entry.getValue());
		}
	}
}
